package com.bci.pwtz.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;

import com.bci.pwtz.common.util.PaginationList;
import com.bci.pwtz.common.util.PwtzUtils;
import com.bci.pwtz.exception.CanNotDeleteException;
import com.bci.pwtz.exception.PwtzDatabaseException;
import com.bci.pwtz.mysql.dao.DykgMapper;
import com.bci.pwtz.mysql.model.Dykg;
import com.bci.pwtz.service.BusinessRefService;
import com.bci.pwtz.service.CompanyService;
import com.bci.pwtz.service.DykgService;

public class DykgServiceImpl implements DykgService
{

    private DykgMapper              objMapper;
    private BusinessRefService businessRefService;
    private CompanyService          companyService;
    private static final Logger     _logger = Logger.getLogger(DykgServiceImpl.class);

    public DykgMapper getObjMapper()
    {
        return this.objMapper;
    }

    public void setObjMapper(DykgMapper objMapper)
    {
        this.objMapper = objMapper;
    }

    public BusinessRefService getBusinessRefService()
    {
        return businessRefService;
    }

    public void setBusinessRefService(BusinessRefService businessRefService)
    {
        this.businessRefService = businessRefService;
    }

    public CompanyService getCompanyService()
    {
        return companyService;
    }

    public void setCompanyService(CompanyService companyService)
    {
        this.companyService = companyService;
    }

    @Override
    public Dykg load(String dykgId) throws PwtzDatabaseException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("load:dykgId=" + dykgId);
        }
        Dykg dykg = null;
        try
        {
            dykg = objMapper.selectByPrimaryKey(dykgId);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (dykg != null)
        {
            _logger.debug("load:result dykg=" + dykg.toString());
        }
        return dykg;
    }

    @Override
    public Dykg add(Dykg dykg) throws PwtzDatabaseException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("add:dykg=" + dykg.toString());
        }
        if (dykg == null)
        {
            if (_logger.isDebugEnabled())
            {
                _logger.debug("add,dykg is null");
            }
            return null;
        }
        else
        {
            /*UUID uuid = UUID.randomUUID();
            dykg.setDeviceid(uuid.toString());*/
            dykg.setStatus(1);
            dykg.setCreatedate(new Date());
            dykg.setLastmodifiedtime(new Date());
        }
        try
        {
            objMapper.insertSelective(dykg);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return dykg;
    }

    @Override
    public int delete(String deviceid) throws PwtzDatabaseException, CanNotDeleteException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("delete:deviceid=" + deviceid);
        }
        int result = 0;
        try
        {
            boolean bl = businessRefService.canDelete("T_DYKG", deviceid);
            if (!bl)
            {
                throw new CanNotDeleteException();
            }
            result = objMapper.deleteById(deviceid,new Date());
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    @Override
    public int update(Dykg dykg) throws PwtzDatabaseException
    {
        if (_logger.isDebugEnabled())
        {
            _logger.debug("update:dykg=" + dykg.toString());
        }
        int result = 0;
        if (dykg == null)
        {
            if (_logger.isDebugEnabled())
            {
                _logger.debug("update,dykg is null");
            }
            return result;
        }else{
            dykg.setLastmodifiedtime(new Date());
        }
        try
        {
            result = objMapper.updateByPrimaryKeySelective(dykg);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        return result;
    }

    @Override
    public PaginationList<Dykg> selectDykgs(String devicename,Long companyId, int portalType,String[] medLineCodes,int stationDeviceType,String stationCode, String beginTime, String endTime, int pageSize, int pageNo) throws PwtzDatabaseException
    {
        PaginationList<Dykg> paginationList = new PaginationList<Dykg>();
        if (_logger.isInfoEnabled())
        {
            _logger.info("findDybx:|devicename=" + devicename+"|beginTime=" + beginTime+"|endTime=" + endTime+"|companyId="+companyId+"|portalType="+portalType+"|medLineCodes="+PwtzUtils.parseCharacterArrayToString(medLineCodes)+"|stationDeviceType="+stationDeviceType+"|stationCode="+stationCode+"|pageSize="+pageSize+"|pageNo="+pageNo);
        }
        List<Dykg> list = null;
        int beginIndex = pageSize * pageNo - pageSize;
        String companyidStr = "";
        String[] companyids = null;
        try
        {
            if (portalType == 1)
            {
                companyidStr = companyService.findChildrensId(companyId,null);
                // System.out.println(companyidStr);
                if (companyidStr != null && companyidStr.length() > 0)
                {
                    companyidStr = companyidStr.substring(0, companyidStr.length() - 1);
                    companyids = companyidStr.split(",");
                }
                // System.out.println(companyids.length);
            }
            list = objMapper.selectDeviceList(devicename,portalType, medLineCodes,stationDeviceType,stationCode,companyids, companyId, beginTime, endTime, beginIndex, pageSize);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (list != null)
        {
            _logger.debug("selectDykgs:result list=" + list.toString());
        }
        int totalCount = 0;
        int totalPage = 1;
        if (pageSize != 0)
        {
            try
            {
                totalCount = objMapper.selectDeviceCount(devicename,portalType,medLineCodes,stationDeviceType,stationCode, companyids, companyId, beginTime, endTime);
                // System.out.println(totalCount);
            }
            catch (DataAccessException e)
            {
                _logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        }
        else
        {
            pageNo = 1;
            if (list != null && list.size() > 0)
            {
                totalCount = list.size();
            }
        }
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(list);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }

    @Override
    public PaginationList<Dykg> selectDykgByDyzf(String stationCode,String deviceName,Long companyId,int pageSize, int pageNo) throws PwtzDatabaseException
    {
        PaginationList<Dykg> paginationList = new PaginationList<Dykg>();
        
        List<Dykg> list = null;
        int benginIndex = pageSize * pageNo - pageSize;
        try
        {
            list = objMapper.selectByDyzf(stationCode, deviceName, companyId, benginIndex, pageSize);
        }
        catch (DataAccessException e)
        {
            _logger.error(ExceptionUtils.getStackTrace(e));
            throw new PwtzDatabaseException();
        }
        if (list!=null)
        {
            _logger.debug("selectDykgByDytg:result menu=" + list.toString());
        }
        int totalCount = 0;
        int totalPage =1;
        if(pageSize!=0){
            try
            {
                totalCount = objMapper.selectDeviceCountByDyzf(stationCode, deviceName, companyId);
            }
            catch (DataAccessException e)
            {
                _logger.error(ExceptionUtils.getStackTrace(e));
                throw new PwtzDatabaseException();
            }
            totalPage = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        }else{
            pageNo=1;
            if(list!=null && list.size()>0){
                totalCount = list.size();
            }
        }
        paginationList.setTotalPage(totalPage);
        paginationList.setCurrPage(pageNo);
        paginationList.setPageSize(pageSize);
        paginationList.setRecords(list);
        paginationList.setTotalRecord(totalCount);
        return paginationList;
    }
}
